<template>
  <div class="login_container">
    <!-- logo -->
    <img src="@/style/images/logo.png" alt="logo" />
    <!-- 标题 -->
    <h1>手机快速登录</h1>
    <van-cell-group :class="{active:isPlayPhone}">
      <van-field
        label="手机号"
        v-model="phone"
        placeholder="请输入手机号"
        label-width="60"
        autocomplete="off"
        @focus="isPlayPhone = true"
        @blur="isPlayPhone = false"
      />
    </van-cell-group>
    <van-cell-group :class="{active:isPlayCode  }">
      <van-field
        label="验证码"
        v-model="code"
        placeholder="请输入验证码"
        label-width="60"
        autocomplete="off"
        @focus="isPlayCode = true"
        @blur="isPlayCode = false"
      >
        <template #button>
          <button @click="getCode" :disabled="!isShowCodeBtn">{{codeMsg}}</button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="loginBtn">
      <van-button block type="info" 
      native-type="submit" 
      @click="onSubmit"
       :disabled="!canSubmit"
       :loading="isloading"
       loading-text="登录中，请稍等"
       loading-type="spinner"
       >登录</van-button>
    </div>
    <div class="checkBox">
      <van-checkbox v-model="agree">
        登陆注册代表同意
        <a href="javascript:void(0)">用户使用协议</a>和
        <a href="javascript:void">隐私政策</a>
      </van-checkbox>
    </div>
    <div class="other">
      <a href="javascript:void(0)">账号密码登录</a>
      <a href="javascript:void(0)">注册新用户</a>
    </div>
  </div>
</template>
<script>
import { loginApi, userInfoApi, userRoleApi, validateApi } from "@/api/userApi";
import { saveAutoToken } from "@/common/localStoreToken";
import { saveToken } from "@/common/sessionStoreToken";
import { getPhone, savePhone } from '../../common/phoneStore';
export default {
  data() {
    return {
      phone: "", // 手机号码
      code: "", // 验证码
      agree: "", // 同意用户须知
      isPlayPhone: false, // 给聚焦的手机号码输入框添加外边框
      isPlayCode: false, // 给聚焦的验证码输入框添加外边框
      codeMsg: "获取验证码", //验证码状态
      isShowCodeBtn: true, //获取验证码按钮是否可用
      isloading:false, //登录加载状态
      
    };
  },
  methods: {
    /**
     * 登录业务
     */
    async onSubmit() {
      if (!this.agree) {
        //判断是否勾选用户隐私
        this.$toast({
          message: "请先勾选同意用户使用协议和隐私政策",
          type: "html"
        });
        return;
      }
      this.isloading = true
      //获取用户信息
      let response = await loginApi({
        phone: this.phone,
        vdtCode: this.code
      });
      let { data, code } = response;
      if (code !== 200) {
        this.$toast({
          message: "用户不存在或者验证码错误！"
        });
        this.isloading = false
        return;
      }
      this.$store.commit("common/SAVE_TOKEN", data.token);
      saveAutoToken(data.token);
      saveToken(data.token);
      //获取角色信息
      let result = await userInfoApi(data.id);
      if (result.code !== 200) {
        this.$toast({
          message: "登录失败，请重试"
        });
        this.isloading = false
        return;
      }
    let roleList = await userRoleApi(result.data.role)
    if (roleList.code !== 200) {
        this.$toast({
          message: "登录失败，请重试"
        });
        this.isloading = false
        return;
      }
      this.$store.commit("common/SAVE_USERINFO", result.data); //存储用户信息
      this.$store.commit("common/SAVE_USERROLE", roleList.data); //存储角色信息(权限)
      savePhone(this.phone)
      this.$router.push("/home");
      this.isloading = false
    },

    /**
     * 获取验证码
     */
    async getCode() {
      let reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
      if (!reg.test(this.phone)) {
        this.$toast({
          message: "请输入11位的正确的手机号码哦！",
          position: "bottom"
        });
        return;
      }
      this.codeMsg = "验证码获取中";
      let result = await validateApi(this.phone);
      if (result.code !== 200) {
        this.$toast({
          message: '"用户不存在或已失效，请重试"',
          position: "bottom"
        });
        this.codeMsg = "获取验证码      ";
        return;
      }
      let { data } = result;
      this.$dialog
        .alert({
          message: `您的验证码是:${data.vdtCode}\n请妥善保管,请勿随意告知他人`
        })
        .then(() => {
          this.loop(Date.now());
        });

      console.log(result, "validateApi");
    },
    /**
     * 再次获取验证码倒计时功能
     * @param {*} st
     */
    loop(st) {
      this.isShowCodeBtn = false;
      let passTime = 30 - (Date.now() - st) / 1000;
      let codeTimer = setTimeout(() => {
        if (passTime > 0) {
          this.codeMsg = `${Math.ceil(passTime)}s后 再次获取`;
          this.loop(st);
          return;
        }
        this.codeMsg = "获取验证码";
        this.isShowCodeBtn = true;
        clearTimeout(codeTimer);
      }, 200);
    }
  },
  watch: {
    phone(val) {
      //必须手机号码输入框输入数字格式
      this.phone = val.replace(/[^0-9]/gi, "");
      this.code = "";
    }
  },
  computed: {
    canSubmit() {
      //提交按钮是否可用
      return (
        /^1[3|4|5|7|8|9][0-9]\d{8}$/.test(this.phone) &&
        /^[0-9]{4}$/.test(this.code) && !this.isloading
      );
    },
    
  },
  created(){
     if(!getPhone() )return
     this.phone = getPhone()  //自动填充手机号
  }
};
</script>
<style lang="less" scoped>
@import "@/style/index.less";
.login_container {
  padding: 10vh 5vw;
  //logo
  > img {
    display: block;
    width: 80px;
    height: 80px;
    margin: auto;
  }
  // 标题
  > h1 {
    font-size: @20;
    line-height: 36px;
    text-align: center;
    font-weight: normal;
    margin-bottom: 30px;
  }
  //输入框包裹盒子
  .van-cell-group {
    border: 1px solid @c9;
    border-radius: 6px;
    margin-bottom: @12;
    //输入框获得焦点样式
    &.active {
      border: 1px solid @c1;
    }
    //验证码按钮
    button {
      color: #1989fa;
      background: #fff;
      border: none;
      &:disabled {
        color: @c9;
      }
    }
  }
  // 提交按钮盒子
  .loginBtn {
    margin: @16 0;
    width: 100%;
    .van-button {
      width: 100%;
      font-size: @16;
      border-radius: 10px;
    }
  }
  //用户须知
  .checkBox {
    padding-bottom: @12;
    margin-bottom: @20;
    /deep/ .van-checkbox__label {
      color: #000;
      font-size: @14;
    }
  }
  //其他操作
  .other {
    display: flex;
    justify-content: space-between;
    font-size: @14;
  }
}
</style>>

